<template>
  <router-link v-if="!user.isLogin" to="/login">
    <el-button type="primary" class="user-profile-component">登录</el-button>
  </router-link>
  <el-dropdown v-else class="user-profile-component" split-button>
    <!-- <router-link to="/setting">{{ user.data.nickName }}</router-link> -->
    <span>{{ user.data.nickName }}</span>
    <template #dropdown>
      <el-dropdown-menu class="user-profile-dropdown">
        <el-dropdown-item @click="createWork">创建作品</el-dropdown-item>
        <el-dropdown-item>
          <router-link to="/works">我的作品</router-link>
        </el-dropdown-item>
        <el-dropdown-item @click="logout">登出</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/stores/user'
import { useEditorStore } from '@/stores/editor'
import { ElMessage } from 'element-plus'

const router = useRouter()
const user = useUserStore()
const editor = useEditorStore()

const createWork = async () => {
  const payload = {
    title: '未命名作品',
    desc: '未命名作品',
    coverImg: 'http://lowcode-backend.oss-cn-shenzhen.aliyuncs.com/lowcode-test/5J8ttm.png'
  }
  const workData = await editor.createWork(payload)
  ElMessage.success({ message: '创建作品成功', duration: 2000 })
  router.push(`/editor/${workData.id}`)
}

const logout = () => {
  user.logout()
  ElMessage.success({ message: '退出登录成功，2秒后跳转到首页', duration: 2000 })
  setTimeout(() => {
    router.push('/')
  }, 2000)
}
</script>
<style lang="scss" scoped>
.user-profile-dropdown {
  border-radius: 2px !important;
}
.user-operation > * {
  margin-left: 30px !important;
}
</style>
